package com.gemme.gemme;

import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.app.Application;
import android.app.Notification;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Handler;
import android.os.Looper;
import android.util.Config;
import android.util.Log;
import android.widget.Toast;

import androidx.multidex.MultiDex;
import androidx.multidex.MultiDexApplication;

import com.gemme.gemme.login.Constant;
import com.gemme.gemme.util.Utils;
import com.hyphenate.EMError;
import com.hyphenate.chat.ChatClient;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMOptions;
import com.hyphenate.easeui.EaseUI;
import com.hyphenate.exceptions.HyphenateException;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.umeng.commonsdk.UMConfigure;
import com.umeng.socialize.PlatformConfig;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareConfig;
import com.umeng.socialize.common.QueuedWork;

import java.util.Iterator;
import java.util.List;
import java.util.Set;

import cn.jpush.android.api.BasicPushNotificationBuilder;
import cn.jpush.android.api.CustomPushNotificationBuilder;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;

@SuppressLint("Registered")
public class GMApplication extends MultiDexApplication {
    protected static final String TAG = "GMApplication";
    private static GMApplication instance;
    public static GMApplication getInstance() {
        return instance;
    }

    @Override
    public void onCreate() {
        super.onCreate();

        instance = this;
        Utils.init(this);
        System.out.println("");
        //初始化极光
        initJiguang();
//        PictureSelector
        MultiDex.install(this);
        //初始化友盟
        initYoumeng();
        //初始化环信   注：EaseUi初始化里已包含SDK的初始化，不需要再去调用SDK的初始化。
//        initHuanxing();
        //初始化环信 easyUI
        initHxEasyUI();
        //初始化客服,暂时禁用环信
        initHuanxinKefu();

        /** 图片加载配置 */
        initImageLoader(getApplicationContext());
    }

    private void initHuanxinKefu() {
        ChatClient.getInstance().init(this, new ChatClient.Options().
                setAppkey("1125200730042918#gemme").setTenantId("84069"));

/*
        ChatClient.getInstance().init(this, new ChatClient.Options().
                setAppkey("1125200730042918#demo").setTenantId("84069"));
*/
    }

    private void initHxEasyUI() {
        EMOptions options = new EMOptions();
// 默认添加好友时，是不需要验证的，改成需要验证  todo 暂时去掉验证
//        options.setAcceptInvitationAlways(false);
        EaseUI.getInstance().init(this, options);
//        addFread();
    }


    private void initHuanxing() {
        EMOptions options = new EMOptions();
    // 默认添加好友时，是不需要验证的，改成需要验证
//        options.setAcceptInvitationAlways(false);  todo 暂时去掉验证
    // 是否自动将消息附件上传到环信服务器，默认为True是使用环信服务器上传下载，如果设为 false，需要开发者自己处理附件消息的上传和下载
        options.setAutoTransferMessageAttachments(true);
    // 是否自动下载附件类消息的缩略图等，默认为 true 这里和上边这个参数相关联
        options.setAutoDownloadThumbnail(true);
    //初始化
        EMClient.getInstance().init(this, options);
    //在做打包混淆时，关闭debug模式，避免消耗不必要的资源
        EMClient.getInstance().setDebugMode(true);


        int pid = android.os.Process.myPid();
        String processAppName = getAppName(pid);
// 如果APP启用了远程的service，此application:onCreate会被调用2次
// 为了防止环信SDK被初始化2次，加此判断会保证SDK被初始化1次
// 默认的APP会在以包名为默认的process name下运行，如果查到的process name不是APP的process name就立即返回

        if (processAppName == null ||!processAppName.equalsIgnoreCase(getPackageName())) {
            Log.e(TAG, "enter the service process!");

            // 则此application::onCreate 是被service 调用的，直接返回
            return;
        }
    }

    private void initYoumeng() {
        //初始化组件化基础库, 所有友盟业务SDK都必须调用此初始化接口。
//建议在宿主App的Application.onCreate函数中调用基础组件库初始化函数。
        UMConfigure.init(this, Constant.YOUMENG_APPKEY, "Umeng", UMConfigure.DEVICE_TYPE_PHONE, "");
        UMConfigure.setLogEnabled(true);
        UMShareAPI.get(this);
        QueuedWork.isUseThreadPool = false;
    //三方获取用户资料时是否每次都要进行授权
        UMShareConfig config = new UMShareConfig();
        config.isNeedAuthOnGetUserInfo(true);
        UMShareAPI.get(this).setShareConfig(config);
    //实现分享和登录
        //微信
        PlatformConfig.setWeixin(Constant.weixin_appid, Constant.weixin_appsecret);
        //新浪
//        PlatformConfig.setSinaWeibo("3921700954", "04b48b094faeb16683c32669824ebdad","http://sns.whalecloud.com");
    }

    private void initJiguang() {
        JPushInterface.setDebugMode(true);
        JPushInterface.init(this);
//        JPushInterface.re
        String registrationID = JPushInterface.getRegistrationID(this);
        System.out.println("");

        // 调用 JPush 接口来设置别名。
        JPushInterface.setAliasAndTags(getApplicationContext(),
                (String) registrationID,
                null,
                new TagAliasCallback() {
                    @Override
                    public void gotResult(int i, String s, Set<String> set) {
                        System.out.println("");
                    }
                });

       /* BasicPushNotificationBuilder builder = new BasicPushNotificationBuilder(this);
        builder.statusBarDrawable = R.drawable.jpush_notification_icon;
        builder.notificationFlags = Notification.FLAG_AUTO_CANCEL
                | Notification.FLAG_SHOW_LIGHTS;  //设置为自动消失和呼吸灯闪烁
        builder.notificationDefaults = Notification.DEFAULT_SOUND
                | Notification.DEFAULT_VIBRATE
                | Notification.DEFAULT_LIGHTS;  // 设置为铃声、震动、呼吸灯闪烁都要
        JPushInterface.setPushNotificationBuilder(1, builder);

        CustomPushNotificationBuilder builder = new
                CustomPushNotificationBuilder(this,
                R.layout.customer_notitfication_layout,
                R.id.icon,
                R.id.title,
                R.id.text,
                R.id.time);
        // 指定定制的 Notification Layout
        builder.statusBarDrawable = R.drawable.your_notification_icon;
        // 指定最顶层状态栏小图标
        builder.layoutIconDrawable = R.drawable.your_2_notification_icon;
        // 指定下拉状态栏时显示的通知图标
        JPushInterface.setPushNotificationBuilder(2, builder);*/

    }


    private String getAppName(int pID) {
        String processName = null;
        ActivityManager am = (ActivityManager) this.getSystemService(ACTIVITY_SERVICE);
        List l = am.getRunningAppProcesses();
        Iterator i = l.iterator();
        PackageManager pm = this.getPackageManager();
        while (i.hasNext()) {
            ActivityManager.RunningAppProcessInfo info = (ActivityManager.RunningAppProcessInfo) (i.next());
            try {
                if (info.pid == pID) {
                    processName = info.processName;
                    return processName;
                }
            } catch (Exception e) {
                // Log.d("Process", "Error>> :"+ e.toString());
            }
        }
        return processName;
    }

    /**
     * 图片加载配置
     */
    public static void initImageLoader(Context context) {
        // This configuration tuning is custom. You can tune every option, you may tune some of them,
        // or you can create default configuration by
        //  ImageLoaderConfiguration.createDefault(this) method.
        ImageLoaderConfiguration.Builder config = new ImageLoaderConfiguration.Builder(context);
        config.threadPriority(Thread.NORM_PRIORITY - 2);
        config.denyCacheImageMultipleSizesInMemory();
        config.diskCacheFileNameGenerator(new Md5FileNameGenerator());
        config.diskCacheSize(50 * 1024 * 1024); // 50 MiB
        config.tasksProcessingOrder(QueueProcessingType.LIFO);
        config.writeDebugLogs(); // Remove for release app

        // Initialize ImageLoader with configuration.
        ImageLoader.getInstance().init(config.build());
    }

}
